<template>
  <view class="login-bg">
    <view class="login-arc-bg"></view>
    <view class="login-content">
      <image class="login-logo" src="/static/logo.png" mode="widthFix" />
      <view class="brand-name gradient-text">{{ app.appTitle }}</view>
      <view class="brand-slogan gradient-text">让管理更高效，让服务更贴心</view>
      <view class="login-form">
        <view class="input-group">
          <view class="input-label">账号</view>
          <view class="input-row">
            <image class="input-icon" src="/static/username.png" />
            <input class="login-input" v-model="form.managerName" type="text" placeholder="请输入账号" />
          </view>
        </view>
        <view class="input-group">
          <view class="input-label">密码</view>
          <view class="input-row">
            <image class="input-icon" src="/static/password.png" />
            <input class="login-input" v-model="form.managerPassword" type="password" placeholder="请输入密码" />
          </view>
        </view>
        <view class="input-group">
          <view class="input-label">验证码</view>
          <view class="input-row captcha-row">
            <image class="input-icon" src="/static/verify.png" />
            <input class="login-input captcha-input" v-model="form.rand_code" type="text" maxlength="4" placeholder="请输入验证码" />
            <view class="captcha-container" @tap="code">
              <image 
                class="captcha-img" 
                :src="captchaUrl" 
                mode="aspectFit"
                @load="onCaptchaLoad"
                @error="onCaptchaError"
              />
              <view class="captcha-loading" v-if="captchaLoading">
                <text>加载中...</text>
              </view>
            </view>
          </view>
        </view>
        <button class="login-btn" @tap="login" :loading="loading">登录</button>
      </view>
      <view v-if="loginError" class="error-tip">{{ loginError }}</view>
    </view>
  </view>
</template>

<script>
import config from '@/config';
import { setSession } from '@/utils/request';

export default {
  data() {
    return {
      baseUrl: config.baseUrl,
      loading: false,
      captchaLoading: true,
      captchaError: false,
      loginError: '',
      app: {
        appTitle: '星屿海',
        appLogo: '',
        appCopyright: '',
        appUrl: '',
      },
      form: {
        managerName: '',
        managerPassword: '',
        rand_code: '',
        rememberMe: true,
      },
      rules: {
        managerName: [
          {required: true, message: '请输入账号', trigger: 'blur'},
          {min: 1, max: 30, message: '长度不能超过30个字符', trigger: 'change'}
        ],
        managerPassword: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 1, max: 30, message: '长度不能超过30个字符', trigger: 'change'}
        ],
        rand_code: [
          {required: true, message: '请输入验证码', trigger: 'blur'},
          {min: 1, max: 4, message: '长度不能超过4个字符', trigger: 'change'}
        ],
      },
      verifCode: "/code.do?t=" + new Date().getTime()
    }
  },
  computed: {
    // 计算完整的验证码URL
    captchaUrl() {
      if (this.captchaError) {
        // 如果加载失败，使用本地备用验证码
        return '/static/captcha.webp';
      }
      return this.baseUrl + this.verifCode;
    }
  },
  created() {
    this.get();
    this.code();
    this.initial();
  },
  methods: {
    // 验证码加载完成
    onCaptchaLoad() {
      this.captchaLoading = false;
      this.captchaError = false;
    },
    
    // 验证码加载失败
    onCaptchaError() {
      this.captchaLoading = false;
      this.captchaError = true;
      console.error('验证码加载失败，使用本地备用验证码');
    },
    
    // 获取验证码
    code() {
      this.captchaLoading = true;
      this.captchaError = false;
      this.verifCode = "/code.do?t=" + new Date().getTime();
      
      // 验证码加载超时处理
      setTimeout(() => {
        if (this.captchaLoading) {
          console.log('验证码加载超时，使用本地备用验证码');
          this.captchaError = true;
          this.captchaLoading = false;
        }
      }, 3000);
    },
    
    // 初始化
    initial() {
      this.form.managerName = uni.getStorageSync('managerName') || '';
      this.form.managerPassword = uni.getStorageSync('managerPassword') || '';
      
      if(uni.getStorageSync('rememberMe') === 'true') {
        this.form.rememberMe = true;
      } else {
        this.form.rememberMe = false;
      }
    },
    
    // 获取应用信息
    get() {
      uni.request({
        url: this.baseUrl + '/basic/app/get.do',
        method: 'GET',
        success: (res) => {
          const result = res.data;
          if (result && result.result) {
            this.app = result.data;
          }
        }
      });
    },
    
    // 表单验证
    validateForm() {
      if (!this.form.managerName) {
        uni.showToast({ title: '请输入账号', icon: 'none' });
        return false;
      }
      if (this.form.managerName.length > 30) {
        uni.showToast({ title: '账号长度不能超过30个字符', icon: 'none' });
        return false;
      }
      if (!this.form.managerPassword) {
        uni.showToast({ title: '请输入密码', icon: 'none' });
        return false;
      }
      if (this.form.managerPassword.length > 30) {
        uni.showToast({ title: '密码长度不能超过30个字符', icon: 'none' });
        return false;
      }
      if (!this.form.rand_code) {
        uni.showToast({ title: '请输入验证码', icon: 'none' });
        return false;
      }
      if (this.form.rand_code.length > 4) {
        uni.showToast({ title: '验证码长度不能超过4个字符', icon: 'none' });
        return false;
      }
      return true;
    },
    
    // 登录
    login() {
      if (!this.validateForm()) {
        return;
      }
      
      this.loading = true;
      this.loginError = '';
      
      // 准备登录参数
      const loginParams = {
        managerName: this.form.managerName,
        managerPassword: this.form.managerPassword,
        rand_code: this.form.rand_code,
        rememberMe: this.form.rememberMe
      };
      
      // 将参数转换为 application/x-www-form-urlencoded 格式
      const formData = Object.keys(loginParams)
        .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(loginParams[key]))
        .join('&');
            
      uni.request({
        url: this.baseUrl + '/ms/login.do',
        method: 'POST',
        data: formData,
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'X-Requested-With': 'XMLHttpRequest'
        },
        success: (res) => {
          
          const result = res.data;
          
          if (result.result) {
            // 保存会话信息和Cookie
            if (res.cookies && res.cookies.length > 0) {
              // 设置会话信息
              setSession({
                cookies: res.cookies,
                sessionId: result.data?.sessionId || ''
              });
              
            }
            
            // 保存用户信息
            if (result.data) {
              // 创建简单的用户信息对象
              const userInfo = {
                sessionId: result.data.sessionId || '',
                loginTime: new Date().getTime()
              };
              uni.setStorageSync('userInfo', JSON.stringify(userInfo));
            }
            
            // 保存账号密码（如果选择了记住我）
            if (this.form.rememberMe) {
              uni.setStorageSync('managerName', this.form.managerName);
              uni.setStorageSync('managerPassword', this.form.managerPassword);
            } else {
              uni.setStorageSync('managerName', '');
              uni.setStorageSync('managerPassword', '');
            }
            uni.setStorageSync('rememberMe', this.form.rememberMe.toString());
            
            // 登录成功提示
            uni.showToast({
              title: '登录成功',
              icon: 'success',
              duration: 1500
            });
            
            // 触发登录成功事件
            uni.$emit('loginSuccess');
            
            // 延迟跳转到首页，让用户看到成功提示
            setTimeout(() => {
              
              // 跳转到首页
              uni.reLaunch({ 
                url: '/pages/index/index',
                fail: (err) => {
                  console.error('跳转失败:', JSON.stringify(err));
                  // 如果跳转失败，尝试其他导航方法
                  uni.switchTab({
                    url: '/pages/index/index'
                  });
                }
              });
            }, 1500);
          } else {
            // 显示错误消息
            this.loginError = result.msg || '登录失败';
            console.error('登录失败:', this.loginError);
            uni.showToast({ 
              title: this.loginError, 
              icon: 'none' 
            });
            this.code();
          }
          this.loading = false;
        },
        fail: (err) => {
          // 打印请求失败信息
          console.error('请求失败:', JSON.stringify(err));
          
          this.loginError = '网络连接错误，无法连接到服务器';
          uni.showToast({ 
            title: this.loginError, 
            icon: 'none' 
          });
          this.code();
          this.loading = false;
        }
      });
    }
  }
}
</script>

<style scoped>
.login-bg {
  min-height: 100vh;
  width: 100vw;
  background: linear-gradient(180deg, #eaf6ff 0%, #f8fbff 60%, #f3f6fa 100%);
  position: relative;
  overflow-x: hidden;
}
.login-arc-bg {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 160vw;
  height: 400rpx;
  background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
  border-bottom-left-radius: 80vw 140rpx;
  border-bottom-right-radius: 80vw 140rpx;
  z-index: 1;
  opacity: 0.95;
}
.login-content {
  position: relative;
  z-index: 2;
  padding: 40px 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.login-logo {
  width: 120px;
  height: auto;
  margin-top: 60px;
  margin-bottom: 20px;
}
.brand-name {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 10px;
}
.brand-slogan {
  font-size: 14px;
  margin-bottom: 40px;
  opacity: 0.8;
}
.gradient-text {
  background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
  -webkit-background-clip: text;
  color: transparent;
  text-align: center;
}
.login-form {
  width: 100%;
  max-width: 320px;
}
.input-group {
  margin-bottom: 20px;
}
.input-label {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}
.input-row {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 8px;
  padding: 12px 15px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.input-icon {
  width: 20px;
  height: 20px;
  margin-right: 10px;
}
.login-input {
  flex: 1;
  font-size: 14px;
  height: 24px;
  line-height: 24px;
}
.captcha-row {
  position: relative;
}
.captcha-input {
  width: 60%;
}
.captcha-container {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  width: 100px;
  height: 40px;
  background-color: #f5f5f5;
  border-radius: 4px;
  overflow: hidden;
}
.captcha-img {
  width: 100%;
  height: 100%;
}
.captcha-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1;
}
.captcha-loading text {
  color: #333;
  font-size: 14px;
}
.login-btn {
  width: 100%;
  height: 46px;
  line-height: 46px;
  background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
  border-radius: 23px;
  color: #fff;
  font-size: 16px;
  font-weight: 500;
  margin-top: 30px;
  box-shadow: 0 4px 12px rgba(79, 172, 254, 0.3);
}

/* 错误信息样式 */
.error-tip {
  margin-top: 15px;
  padding: 10px;
  background-color: rgba(255, 0, 0, 0.1);
  border-radius: 5px;
  color: #ff3333;
  font-size: 14px;
  text-align: center;
}

/* 调试信息样式 */
.debug-info {
  margin-top: 20px;
  padding: 10px;
  background-color: rgba(0, 0, 0, 0.05);
  border-radius: 5px;
  color: #666;
  font-size: 12px;
  white-space: pre-line;
}
</style> 